<?php
/**
 * 认证用户后台登录
 *
 * @author    wangmx <wangmx@yunys.com.cn>
 * @copyright 2016 QuanZhouYunYiShang Inc.
 */
namespace App\Services\AuthenticationUserService;

use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use Session;
use App\Services\UserService\UserTool;
use App\Services\ProductsService\ProductTool;
use App\Services\UserService\CCPRestSmsSDK;
use App\Services\ProductsService\ProductsService;

class AuthenticationUserService
{
    protected $UserTool;
    protected $Product;
    protected $product;


    public function __construct(UserTool $UserTool,ProductTool $Product,ProductsService $productSer)
    {
        $this->UserTool = $UserTool;
        $this->Product = $Product;
        $this->product = $productSer;
    }
    /**
     * @param Request $request
     * @return array
     * 认证后台登录
     * 手机号 短信验证码登录
     * 只允许认证用户登录
     */
    public function authenticationLogin(Request $request)
    {
        $phone = $request->get('phone');
        $captcha = $request->get('captcha');
        $user_id = DB::table('users')->where('phone', $phone)->value('user_id');
        $user_type = $this->UserTool->userType($user_id);
        if ($user_type == 0) {
            $result = array('message' => '非认证用户', 'result' => (object)array(), 'state' => 'M10001');
            return $result;
        }
        $checkResult = $this->checkIdentifying($phone, $captcha);
        if ($checkResult['state'] != 'M00000') {//M01002[验证码超时,请重新获取] M01003[验证码不正确,请重新输入]
            return $checkResult;
        }

        $userinfo = DB::table('users')->where('phone', $phone)->first();
        $user_id = $userinfo->user_id;
        $request->session()->put('user_type', $user_type);//1设计师 2品牌
        $request->session()->put('user_id', $user_id);
        $request->session()->put('userinfo', $userinfo);
        $userinfo = $this->UserTool->checkHeader($userinfo);
        $userinfo = $this->UserTool->checkCoverMap($userinfo);
        $follow_num = $this->UserTool->followNum($user_id);
        $fans_num = $this->UserTool->fansNum($user_id);
        $create_num = $this->Product->getProductNumByUserID($user_id);
        $userinfo->follow_num = $follow_num;
        $userinfo->create_num = $create_num;
        $userinfo->fans_num = $fans_num;
        $result = array('message' => '登录成功', 'result' => $userinfo, 'state' => 'M00000');
        return $result;
    }

    /**
     * @param Request $request
     * @return array
     * 发送验证码
     */
    function sendCaptcha(Request $request)
    {
        $phone = $request->input('phone');
        $user_type = DB::table('users')->where('phone', $phone)->value('user_type');
        if ($user_type == 0 || $user_type == null) {
            $arr = array('message' => '只允许认证用户登录', 'result' => (Object)array(), 'state' => 'M09005');
            return $arr;
        }
        $accountSid = env('accountSid');
        //主帐号令牌,对应官网开发者主账号下的 AUTH TOKEN
        $accountToken = env('accountToken');
        //应用Id，在官网应用列表中点击应用，对应应用详情中的APP ID
        //在开发调试的时候，可以使用官网自动为您分配的测试Demo的APP ID
        $appId = env('appId');
        //请求地址
        //沙盒环境（用于应用开发调试）：sandboxapp.cloopen.com
        //生产环境（用户应用上线使用）：app.cloopen.com
//        $serverIP = 'app.cloopen.com';
        $serverIP = 'sandboxapp.cloopen.com';
        //请求端口，生产环境和沙盒环境一致
        $serverPort = '8883';
        //REST版本号，在官网文档REST介绍中获得。
        $softVersion = '2013-12-26';
        // 初始化REST SDK
        $rest = new CCPRestSmsSDK($serverIP, $serverPort, $softVersion);
        $rest->setAccount($accountSid, $accountToken);
        $rest->setAppId($appId);
        $random = $rest->random(4);
        $time = time();
        $datas = array("$random", "5");//发送给用户的验证码 和 有效时间
        // 发送模板短信
        $to = $request->input('phone');
        $tempId = env('tempId');
        $result = $rest->sendTemplateSMS($to, $datas, $tempId);
        $code = $result->statusCode;
        $codes = json_decode($code);
        $access_type = $this->UserTool->Type($to);
        $hasPhone = DB::table('identifyings')->where('phone', $to)->first();
        if ($hasPhone != null) {
            $time = DB::table('identifyings')->where('phone', $to)->value('created_at');
            $diffTime = time() - $time;
            if ($diffTime < 60) {//验证短信验证码是否1分钟内
                $arr = array('message' => '验证码已发送,请查看短信', 'result' => (Object)array(), 'state' => 'M09004');
                return $arr;
            }
        }
        if ($codes == 160040) {
            $arr = array('message' => '该号码发送验证码已达上限', 'result' => (Object)array(), 'state' => 'M09003');
            return $arr;
        }
        if ($codes == 000000) {
            DB::table('identifyings')->where('phone', $phone)->delete();
            DB::table('identifyings')->insert(
                array(
                    'identifying' => $random,
                    'phone' => $to,
                    'created_at' => time(),
                    'updated_at' => time()
                )
            );
            $result = array(
                'access_type' => $access_type);
            $arr = array('message' => '验证码发送成功', 'result' => $result, 'state' => 'M00000');
            return $arr;
        } else {
            $arr = array('message' => '系统繁忙,请稍后重试', 'result' => (Object)array(), 'state' => 'M01001');
            return $arr;
        }
    }

    /**
     * 检查验证码
     */
    public function checkIdentifying($phone, $identifying)
    {
        $random = DB::table('identifyings')->where('phone', $phone)->value('identifying');//验证码
        if ($random == null) {
            $result = array('message' => '请先获取验证码', 'result' => (object)array(), 'state' => 'M01001');
            return $result;
        }
        $time = time();
        $random_time = DB::table('identifyings')->where('phone', $phone)->value('created_at');//获取验证码的时间
        //验证码超时
        if ($time - $random_time > 300) {//5分钟
            DB::table('identifyings')->where('phone', $phone)->delete();
            $result = array('message' => '验证码超时,请重新获取', 'result' => (object)array(), 'state' => 'M01002');
            return $result;
        }
        //验证码不正确
        if ($identifying != $random) {
            $result = array('message' => '验证码不正确,请重新输入', 'result' => (object)array(), 'state' => 'M01003');
            return $result;
        } else {
            //验证码验证正确
            DB::table('identifyings')->where('phone', $phone)->delete();
            $result = array('message' => '成功', 'result' => (object)array(), 'state' => 'M00000');
            return $result;
        }
    }

    public function userCenter($user_id){
        $userinfo = DB::table('users')->where('user_id', $user_id)->first();
        $userinfo = $this->UserTool->checkHeader($userinfo);
        $userinfo = $this->UserTool->checkCoverMap($userinfo);
        $follow_num = $this->UserTool->followNum($user_id);
        $fans_num = $this->UserTool->fansNum($user_id);
        $create_num = $this->getAllProductNumByUserID($user_id);
        $userinfo->follow_num = $follow_num;
        $userinfo->create_num = $create_num;
        $userinfo->fans_num = $fans_num;
        $data = $this->product->get_list_by_user_id($user_id,9);
        $list  = $data['result']['data'];
        return array('list'=>$list,'userinfo'=>$userinfo);
    }


    public function getAllProductNumByUserID($user_id)
    {
        $create_num = DB::table('products')->where(['user_id'=>$user_id,'is_shelves' => 1,'state'=>1])->count();
        return $create_num;
    }

}